package com.sci.util;

import com.sci.entity.User;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;

@Component
public class JwtTokenUtil {

    @Value("${jwt.base-secret}")
    private String baseSecret;

    public boolean validateToken(String token) {
        try {
            System.out.println("=== Token Validation Debug ===");
            System.out.println("Token to validate: " + token);
            System.out.println("Using base secret: " + baseSecret);

            Jws<Claims> jws = Jwts.parser()
                    .verifyWith(createHmacShaKey(baseSecret))
                    .build()
                    .parseSignedClaims(token);

            Claims claims = jws.getPayload();
            System.out.println("Token parsed successfully:");
            System.out.println("Subject (user ID): " + claims.getSubject());
            System.out.println("Issuer: " + claims.getIssuer());
            System.out.println("Expiration: " + claims.getExpiration());
            System.out.println("Issued At: " + claims.getIssuedAt());

            return true;
        } catch (ExpiredJwtException e) {
            System.err.println("Token expired: " + e.getMessage());
            throw new SecurityException("令牌已过期", e);
        } catch (UnsupportedJwtException e) {
            System.err.println("Unsupported JWT: " + e.getMessage());
            throw new SecurityException("无效的令牌", e);
        } catch (MalformedJwtException e) {
            System.err.println("Malformed JWT: " + e.getMessage());
            throw new SecurityException("无效的令牌", e);
        } catch (SignatureException e) {
            System.err.println("Signature mismatch: " + e.getMessage());
            throw new SecurityException("无效的令牌", e);
        } catch (IllegalArgumentException e) {
            System.err.println("Illegal argument: " + e.getMessage());
            throw new SecurityException("无效的令牌", e);
        }
    }

    public String getUserIdFromToken(String token) {
        try {
            Claims claims = Jwts.parser()
                    .verifyWith(createHmacShaKey(baseSecret))
                    .build()
                    .parseSignedClaims(token)
                    .getPayload();
            System.out.println("Extracted user ID from token: " + claims.getSubject());
            return claims.getSubject();
        } catch (Exception e) {
            System.err.println("Failed to get user ID from token: " + e.getMessage());
            throw e;
        }
    }

    private SecretKey createHmacShaKey(String secret) {
        byte[] keyBytes = secret.getBytes(StandardCharsets.UTF_8);
        return Keys.hmacShaKeyFor(keyBytes);
    }

    public String getBaseSecret() {
        return baseSecret;
    }
}